﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Clinica_Frba.Login;
using System.Security.Cryptography;  


namespace Clinica_Frba.NewFolder10
{    
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            myConnection.Open();
            usuario = new Usuario();
            
            
        }
        SqlConnection myConnection = new SqlConnection(publico.ConnectionString);
        Usuario usuario;
        
        private void Form1_Load(object sender, EventArgs e)
        {
            
        }
        
        int fallidos = 0;
        private void logInAccess()
        {
            getInfoUsuario();
            SqlCommand consulta = new SqlCommand("select * from USUARIO where Usuario='" + usuario.username + "'and Password='" + SHA256Encrypt(usuario.password) + "'", myConnection);
                SqlDataReader executeCMD = consulta.ExecuteReader();

                executeCMD.Read();
                
                
           
                if (executeCMD.HasRows)
                {   
                    if(Convert.ToBoolean(executeCMD["Banned"])==true)
                    {
                        MessageBox.Show("Banned User. Contact Admin, Shutting down.");
                        Application.ExitThread();
                        
                        
                    }
     
                    MessageBox.Show("Succesfull Log In");
                    publico.usuarioLogueado = usuario;
                    
                    this.Hide();
                    //List<string> listaRols = getRols(usuario.username);
                    int id_usu = executeCMD.GetInt32(0);
                    Form2 f2 = new Form2(id_usu);
                    f2.Show();

                    string id_prof = Convert.ToString(executeCMD["id_prof"]);

                    executeCMD.Close();

                    publico.rolesUsuarioLogueado = getRols(usuario.username);

                    if(publico.rolesUsuarioLogueado.Contains("Profesional"))
                    {
                        publico.idProfesionalLogueado = id_prof;
                    }
                    if (publico.rolesUsuarioLogueado.Contains("Administrativo"))
                    {
                        publico.idProfesionalLogueado = id_prof;
                    }
                }
                else
                {
                    
                    fallidos++;
                    MessageBox.Show("Try Again, Failed Attempts " + fallidos + "/3");
                    executeCMD.Close();
                   

                    if (fallidos == 3)
                    {
                        MessageBox.Show("3 Log In Failures * User Banned Contact an Admin* ... Shutting down.");
                        banUser(usuario.username);
                        myConnection.Close();
                        Application.ExitThread();
                    }
                    txtUser.Clear();
                    txtPassword.Clear();
                    txtUser.Focus();
                }
        }

        public List<string> getRols(string user)
        {
            string query = "SELECT NOMBRE_ROL FROM USUARIO USU JOIN ROL_USUARIO RU ON USU.ID_USU = RU.ID_USU LEFT JOIN ROL R ON RU.ID_ROL=R.ID_ROL WHERE USU.Usuario='" + user + "'";
            SqlCommand command = new SqlCommand(query, myConnection);
            SqlDataReader myreader;
            myreader = command.ExecuteReader();            
            List<string> rols = new List<string>();
            while (myreader.Read())
            {
                
                string sRol=myreader.GetString(0);
                rols.Add(sRol);
                    
                    
            }

            return rols;
        }

        public void getInfoUsuario()
        {            
            usuario.username = txtUser.Text;
            usuario.password = txtPassword.Text;          
        }

        public void LogIn_Click(object sender, EventArgs e)
        {
            logInAccess();                     
        }

        private void txtPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                logInAccess();
            }
        }
        private void banUser(string user)
        {
            SqlCommand consulta = new SqlCommand("Update USUARIO set Banned=1 where Usuario='"+user+"'", myConnection);
            SqlDataReader executeCMD = consulta.ExecuteReader();
        }

        public string SHA256Encrypt(string input)   //punto de encriptacion
        {
            SHA256CryptoServiceProvider provider = new SHA256CryptoServiceProvider();

            byte[] inputBytes = Encoding.UTF8.GetBytes(input);
            byte[] hashedBytes = provider.ComputeHash(inputBytes);

            StringBuilder output = new StringBuilder();

            for (int i = 0; i < hashedBytes.Length; i++)
                output.Append(hashedBytes[i].ToString("x2").ToLower());

            return output.ToString();
        }  
    }
}
